package tag;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;

import toolkit.CollectionUtils;
import toolkit.Debug;
import bean.PizzaBean;
import domain.value.Ingredient;

public class CustomPizzaTag extends AbstractTag
{
	private Tag tag = null;
	
	private PageContext pageContext = null;
	
	private List<PizzaBean> pizzas = null;
	
	public CustomPizzaTag()
	{
		Debug.log("(" + id + ") CustomPizzaTag()");
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public int doStartTag() throws JspException
	{
		Debug.log("(" + id + ") CustomPizzaTag.doStartTag()");
		
		String body = "<div id=\"pizzalist\">";
		
		if (pizzas == null || pizzas.size() == 0)
		{
			body += "Er zijn geen pizzas beschikbaar.";
		}
		else
		{
			int dayOfWeek = new GregorianCalendar().get(Calendar.DAY_OF_WEEK);
			
			for (PizzaBean bean: pizzas)
			{
				try
				{
					String name = (String) bean.get("name");
					
					ArrayList<Ingredient> ingredients = (ArrayList<Ingredient>) bean.get("ingredients");
					
					String price = (String) bean.get("price");
					
					int discountDay = Integer.parseInt((String) bean.get("discountDay"));

					String ingrString;
					
					if (ingredients != null && ingredients.size() > 0)
					{
						ingrString = CollectionUtils.join(ingredients, ", ");;
					}
					else
					{
						ingrString = "Onbekend";
					}
					
					body += ("<div class=\"pizza" + (dayOfWeek == discountDay ? " highlite":"") + "\">" +
								"<strong>" + name + "</strong>" +
								"<div class=\"price\">&euro; " + price + "</div>" +
								"<p>Ingredi&euml;nten: " + ingrString + "</p>" +
							"</div>");
				}
				catch (Exception e)
				{
					Debug.log(e);
				}
			}
		}
		
		body += "</div>";
		
		try
		{
			pageContext.getOut().print(body);
		}
		catch (IOException e)
		{
			Debug.log(e);
		}
		
		return EVAL_PAGE;
	}
	
	@Override
	public int doEndTag() throws JspException
	{
		Debug.log("(" + id + ") CustomPizzaTag.doEndTag()");
		
		return SKIP_BODY;
	}
	
	@Override
	public void setParent(Tag tag)
	{
		Debug.log("(" + id + ") CustomPizzaTag.setParent(" + tag + ")");
		
		this.tag = tag;
	}
	
	@Override
	public Tag getParent()
	{
		Debug.log("(" + id + ") CustomPizzaTag.getParent()");
		
		return tag;
	}
	
	@Override
	public void setPageContext(PageContext pageContect)
	{
		Debug.log("(" + id + ") CustomPizzaTag.setPageContext(" + pageContect + ")");
		
		pageContext = pageContect;
	}
	
	public void setBeans(List<PizzaBean> beans)
	{
		Debug.log("(" + id + ") CustomPizzaTag.setBeans(" + beans + ")");
		
		pizzas = beans;
	}
	
	@Override
	public void release()
	{
		Debug.log("(" + id + ") CustomPizzaTag.release()");
	}
	
	@Override
	protected void finalize() throws Throwable
	{
		Debug.log("(" + id + ") CustomPizzaTag.finalize()");
	}
}
